package com.chaofan.sell.controller;

import com.chaofan.sell.entity.ProductCategory;
import com.chaofan.sell.entity.ProductInfo;
import com.chaofan.sell.service.ProductService;
import com.chaofan.sell.utils.ResultVOUtil;
import com.chaofan.sell.vo.ProductInfoVO;
import com.chaofan.sell.vo.ProductVO;
import com.chaofan.sell.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 买家商品
 *
 * @author: Fairy
 * @date: 2021/9/6
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {
 
    @Autowired
    private ProductService productService;

    @GetMapping("/list")
//    @Cacheable(cacheNames = "product", key = "123")
    public ResultVO list() {
        //1. 查询上架商品
        List<ProductInfo> productList = productService.findUpAll();

        //2. 查询类目
        List<Integer> collect = productList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());

        List<ProductCategory> categoryTypeList = productService.findByCategoryTypeIn(collect);
        //3. 数据拼装
        List<ProductVO> productVOList = new ArrayList<>();

        for (var category : categoryTypeList) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryType(category.getCategoryType());
            productVO.setCategoryName(category.getCategoryName());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (var product : productList) {
                if (product.getCategoryType().equals(category.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(product, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultVOUtil.success(productVOList);
    }
}
